import { Controller, Post, Get, Param, Body, Query, Res, Req, Logger } from '@nestjs/common';
import { IsNotEmpty } from 'class-validator';
import { Request } from 'express';
import { ApiException } from 'src/exception/api.exception';
import { UserService } from 'src/service/user/user.service';

import { LoginEntity, LoginRequest, ResultBean } from '../../types'


class NameEntity {
    @IsNotEmpty({ message: "名称不能为空" })
    name: string

}

@Controller('/sv')
export class UserController {

    private readonly logger = new Logger(UserController.name);

    constructor(readonly userService: UserService) { }

    @Post("/login")
    async login(@Req() req: Request, @Body() loginEntity: LoginEntity): Promise<ResultBean> {

        let vc = (req as any).session.emails[loginEntity.email]

        if (vc != loginEntity.vcode) {
            throw new ApiException("验证码错误")
        }

        delete (req as any).session.emails[loginEntity.email]

        let token: string = await this.userService.login(loginEntity.email);

        const res = ResultBean.success(null);
        (res as any).token = token

        return res;

    }


    @Get("/getUserInfo")
    async getUserInfo(@Req() req: LoginRequest): Promise<ResultBean> {
        const uid: string = req.currentUser();
        const userInfo = await this.userService.getUserInfo(Number(uid))
        return ResultBean.success(userInfo);
    }

    @Post("/setUserInfo")
    async setUserInfo(@Req() req: LoginRequest, @Body() nameHolder: NameEntity): Promise<ResultBean> {

        const uid: string = req.currentUser();
        await this.userService.setUserName(Number(uid), nameHolder.name)

        return ResultBean.successMsg("修改成功")
    }
}
